import React from "react";
import {Map, Marker, MouseTool} from "react-amap";
import BaseComponent from "components/Base/BaseComponent";
import PropTypes from "prop-types";

export default class extends BaseComponent {

  static propTypes = {
    onChose: PropTypes.func,
  };

  constructor() {
    super();
    const self =this;
    this.amapEvents = {
      created: (mapInstance) => {
        this.setState({"map": mapInstance});
      }
    };

    this.toolEvents = {
      created: (tool) => {
        console.log(tool)
        self.tool = tool;
        tool.marker();
      },
      draw({obj}) {
        self.tool.close(true);
        const {lng, lat} = obj.getPosition();
        !!self.props.onChose && self.props.onChose(lng,  lat);
        self.tool.marker();
      }
    }
  }

  render() {

    const {lng, lat} = this.props;

    const plugins = [
      'Scale',
      {
        name: 'ToolBar',
        options: {
          visible: true,  // 不设置该属性默认就是 true
          onCreated(ins) {
            console.log(ins);
          },
        },
      }
    ];

    const mapProps = {
      version: '1.4.15',
      amapkey: '2d414d215b304de20e3863a1bc3afc76',
      plugins,
      zoom: 16,
      events: this.amapEvents,
      center: ((!!lng && !!lat) ? {longitude: lng, latitude : lat}: undefined),
      ...this.props,
    }

    return (
      <Map {...mapProps}>
        <MouseTool events={this.toolEvents}/>
        {
          (!!lng && !!lat) ? <Marker position={{longitude: lng, latitude : lat}} />: undefined
        }
        {this.props.children}
      </Map>
    );
  }

}
